package com.pat.java.base.socket;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class SimpleWebServer {
	public static void main(String args[]) {
		ServerSocket serverSocket = null;
		Socket clientSocket = null;
		int connects = 0;
		try {
			//创建服务器Socket，端口82，限制5个连接
			serverSocket = new ServerSocket(12000, 5);
			while (connects < 5) {
				//等待连接
				clientSocket = serverSocket.accept();
				//操作连接
				ServiceClient(clientSocket);
				connects++;
			}
			serverSocket.close();
		}catch (IOException ioe) {
			System.out.println("Error in SimpleWebServer: " + ioe);
		}
	}

	@SuppressWarnings("deprecation")
	public static void ServiceClient(Socket client) throws IOException {
		DataInputStream inbound = null;
		DataOutputStream outbound = null;
		try {
			//获得输入输出流
			inbound = new DataInputStream(client.getInputStream());
			outbound = new DataOutputStream(client.getOutputStream());
			StringBuffer buffer = new StringBuffer("\"http:www.xjtu.edu.cn/\"\r\n");
			String inputLine;
			while ((inputLine = inbound.readLine()) != null) {
				//判断输出为hello的字符串
				if (inputLine.equals("hello")) {
					outbound.writeBytes(buffer.toString());
					break;
				}
			}
		} finally {
			//打印清除连接，关闭流及Socket
			System.out.println("Cleaning up connection: " + client);
			outbound.close();
			inbound.close();
			client.close();
		}
	}
}